<template>
  <div>
    <el-row style="padding-top: 100px">
      <el-col :span="8" :offset="8">
        <el-form
          :model="ruleForm"
          status-icon
          :rules="rules"
          ref="refForm"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item label="账号" prop="username">
            <el-input v-model="ruleForm.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input
              type="password"
              v-model="ruleForm.password"
              autocomplete="off"
              @keydown.enter="submitForm('ruleForm')"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitForm('ruleForm')"
              >登录</el-button
            >
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { toRefs, reactive, ref } from "vue";
import { useRouter } from "vue-router";
import { login } from "@/api/article";
import { setToken } from "@/utils/token";
import md5 from "md5";
import { useStore } from "vuex";
export default {
  setup() {
    const data = reactive({
      ruleForm: {
        username: "",
        password: "",
      },
      rules: {
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
        username: [{ required: true, message: "请输入账号", trigger: "blur" }],
      },
    });
    const refForm = ref(null);
    const router = useRouter();
    const store = useStore();
    function submitForm() {
      refForm.value.validate((valid) => {
        if (valid) {
          login({
            username: data.ruleForm.username,
            password: md5(data.ruleForm.password),
          }).then((res) => {
            if (res.code == 200) {
              setToken(res.data.token);
              store.dispatch("setUserName", data.ruleForm.username);
              router.push("/index");
            }
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    }
    return { ...toRefs(data), submitForm, refForm };
  },
};
</script>

<style lang="scss" scoped></style>
